package org.garbagecan.springstudy.dao.jdbc;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class UserDaoJdbcImpl4 extends JdbcDaoSupport implements UserDao {

	public User add(User user) {
		this.getJdbcTemplate().update("insert into user (id, name, password) values (?, ?, ?)",
			new Object[] {user.getId(), user.getName(), user.getPassword()});
		return user;
	}

	public void update(User user) {
		this.getJdbcTemplate().update("update user set name=?, password=? where id=?",
			new Object[] {user.getName(), user.getPassword(), user.getId()});
	}

	public void delete(User user) {
		this.getJdbcTemplate().update("delete from user where id=?", new Object[] {user.getId()});
	}
	
	public User findById(String id) {
		String sql = "select id, name, password from USER where id = ?";
		RowMapper mapper = new RowMapper() {
			public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
				User user = new User();
				user.setId(rs.getString("id"));
				user.setName(rs.getString("name"));
				user.setPassword(rs.getString("password"));
				return user;
			}
		};
		return (User) getJdbcTemplate().queryForObject(sql, new Object[]{id}, mapper);
	}

	public List<User> list() {
		String sql = "select id, name, password from USER";
		RowMapper mapper = new RowMapper() {
			public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
				User user = new User();
				user.setId(rs.getString("id"));
				user.setName(rs.getString("name"));
				user.setPassword(rs.getString("password"));
				return user;
			}
		};
		List<User> users = getJdbcTemplate().query(sql, mapper);
		return users;
	}
}
